<template>
  <div class="cq-container">
    <div class="cq-header-box">
      <div class="cq-header-title">
        <div>综合查询</div>
        <div>
          <el-button size="small" type="primary" @click="handleShow">{{
            showQuery ? '收起' : '展开'
          }}</el-button>
        </div>
      </div>
      <el-collapse-transition>
        <div v-show="showQuery" class="cq-header">
          <FilterBar
            :allFields="allFields"
            :operators="allOperators"
            @query="handleQuery"
          />
        </div>
      </el-collapse-transition>
    </div>

    <div class="cq-body">
      <div class="cq-side" ref="cqSide" v-loading="loadingFields">
        <QuerySide
          :allFields="allFields"
          :selectedFields="selectedFields"
          @addField="handleAddField"
          @removeField="handleRemoveField"
        />
      </div>

      <div class="cq-result" ref="cqResult" v-loading="loadingTableData">
        <div v-if="selectedFields.length === 0" class="empty-div">
          <div v-if="!loadingFields" class="empty-tip">请选择列以开始</div>
        </div>
        <div v-else class="result-div">
          <div class="table-div">
            <el-table
              stripe
              border
              fit
              style="width:100%"
              :height="tableHeight"
              :data="queryResult"
            >
              <el-table-column
                v-for="col in selectedFields"
                :key="'col_' + col.tableId"
                :prop="col.fieldEnName"
                :label="col.fieldZhName"
              >
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="100"
                header-align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="basicData(scope.row)"
                    >查看</el-button
                  >
                  <el-button type="text" size="small">下载</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="page-div">
            <el-pagination
              background
              layout="prev, pager, next"
              hide-on-single-page
              :page-size="pageSize"
              :pager-count="11"
              :total="queryResultCount"
              :current-page.sync="pageNum"
              @prev-click="handlePrevClick"
              @next-click="handleNextClick"
              @current-change="handleCurrentChange"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui';
import Sortable from 'sortablejs';
import { v4 as guid } from 'uuid';

import FilterBar from './components/filterBar.vue';
import QuerySide from './components/querySide.vue';
import { fieldTypes, queryTypes, boolTypes } from './queryDef';

import { nl_set_cookie, nl_get_cookie } from '@/utils/cookie';

const fieldsCookieKey = 'cookie_fields';
const fieldStorageKey = 'store_field';

export default {
  name: 'comprehensiveQuery',
  components: {
    FilterBar,
    QuerySide,
  },
  data() {
    return {
      allFields: [],
      allOperators: [],

      selectedFields: [], // 已选字段
      selectedFieldsCount: 0,

      queryCondition: {
        match_all: {},
      },
      sort: [],
      pageNum: 1, // 分页
      pageSize: 50,

      queryResult: [],
      queryResultCount: 0,

      showQuery: false,
      tableHeight: 600,

      sortAble: null, // 表格拖拽列

      // loading:
      loadingFields: false,
      loadingTableData: false,
    };
  },
  computed: {},
  watch: {
    selectedFields: {
      handler(newVal) {
        const selectedFieldsCount = newVal.length;

        if (
          selectedFieldsCount > 0 &&
          selectedFieldsCount > this.selectedFieldsCount
        ) {
          this.$nextTick(() => {
            this.enableColDrop();
          });
        }

        this.selectedFieldsCount = selectedFieldsCount;
      },
    },
  },
  created() {
    // 1. 获取所有字段
    this.loadingFields = true;
    this.$store
      .dispatch('getOptionalField_action')
      .then(res => {
        if (res.statusCode === 200) {
          this.allFields = res.data;

          let noSavedField = true;

          const fields_cookie_str = nl_get_cookie(fieldsCookieKey);
          if (fields_cookie_str) {
            const storedFields = JSON.parse(fields_cookie_str);
            if (storedFields.length > 0) {
              noSavedField = false;
            }

            for (let fieldId of storedFields) {
              const field = this.allFields.find(x => x.id === fieldId);
              field.tableId = guid();
              this.selectedFields.push(field);
            }
          }

          if (noSavedField) {
            for (let field of this.allFields) {
              if (field.defaultSelect) {
                field.tableId = guid();
                this.selectedFields.push(field);
              }
            }
          }
        }
        this.loadingFields = false;
      })
      .catch(err => {
        console.error(err);
        this.loadingFields = false;
      });

    // 2. 获取所有操作
    this.allOperators = queryTypes;

    // 3. 请求数据
    this.execQuery();
  },
  mounted() {
    this.$nextTick(() => {
      window.addEventListener('resize', this.getHeight);
      this.getHeight();
    });
  },
  destroyed() {
    window.removeEventListener('resize', this.getHeight);
  },
  methods: {
    getHeight(event) {
      this.tableHeight = window.innerHeight - 300;
      if (event) {
        console.log('resize: ', event);
        event => event.preventDefault();
      }
    },
    enableColDrop() {
      const wrapperTr = document.querySelector('.has-gutter tr');

      if (wrapperTr) {
        console.log('设置拖拽');
        console.log('wrapperTr: ', wrapperTr);

        this.sortAble = Sortable.create(wrapperTr, {
          animation: 180,
          delay: 0,
          onEnd: evt => {
            console.log('拖拽列');
            console.log('old: ', evt.oldIndex);
            console.log('new: ', evt.newIndex);

            if (evt.oldIndex !== evt.newIndex) {
              const oldItem = this.selectedFields[evt.oldIndex];
              oldItem.tableId = guid();

              this.selectedFields.splice(evt.oldIndex, 1);

              for (let field of this.selectedFields) {
                field.tableId = guid();
              }

              this.selectedFields.splice(evt.newIndex, 0, oldItem);

              this.saveFields();
            }
          },
        });
      }
    },
    handleAddField(field) {
      // if (this.selectedFields.length === 0) {
      //   field.fixed = 'left';
      // }
      field.tableId = guid();
      this.selectedFields.push(field);
      this.saveFields();
    },
    handleRemoveField(field) {
      let i;
      for (i = 0; i < this.selectedFields.length; i++) {
        if (this.selectedFields[i].id === field.id) {
          this.selectedFields.splice(i, 1);
          break;
        }
      }

      // if (i === 0 && this.selectedFields.length > 0) {
      //   this.selectedFields[0].fixed = 'left';
      // }

      this.saveFields();
    },

    handleShow() {
      this.showQuery = !this.showQuery;
    },
    handleQuery(queryCondition) {
      if (!queryCondition || JSON.stringify(queryCondition) === '{}') {
        queryCondition = {
          match_all: {},
        };
      }

      this.queryCondition = queryCondition;
      this.pageNum = 1;

      this.execQuery();
    },
    execQuery() {
      this.loadingTableData = true;

      const queryCondition = this.queryCondition;
      const sort = this.sort;
      const rowBounds = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };

      const queryData = {
        queryCondition,
        sort,
        rowBounds,
      };

      this.$store
        .dispatch('getTableData_action', queryData)
        .then(res => {
          if (res.statusCode === 200) {
            const { records, count } = res.data;

            this.queryResult.splice(0, this.queryResult.length, ...records);
            this.queryResultCount = count;
          }

          this.loadingTableData = false;
        })
        .catch(err => {
          // console.error(err);
          Message({
            message: '查询条件错误',
            type: 'error',
            duration: 5 * 1000,
          });

          this.queryResult.splice(0, this.queryResult.length);
          this.queryResultCount = 0;
          this.loadingTableData = false;
        });
    },
    saveFields() {
      const selectedFieldsId = this.selectedFields.map(x => x.id);
      console.log('selectedFieldsId: ', selectedFieldsId);
      nl_set_cookie(fieldsCookieKey, JSON.stringify(selectedFieldsId));
    },
    handlePrevClick() {
      if (this.pageNum > 1) {
        this.pageNum--;
        this.execQuery();
      }
    },
    handleNextClick() {
      const totalPage = Math.ceil(this.queryResultCount / this.pageSize);
      if (this.pageNum < totalPage) {
        this.pageNum++;
        this.execQuery();
      }
    },
    handleCurrentChange() {
      this.execQuery();
    },

    // 列操作
    basicData(row) {
      console.log(row);
      localStorage.setItem(fieldStorageKey, JSON.stringify(row));

      this.$router.push({ path: './BasicInfo', query: { id: row.id } });
    },
  },
};
</script>

<style scoped>
.cq-container {
  position: relative;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  user-select: none;
  visibility: visible;
  z-index: 1;
  background: #fefefe;
}

.cq-header-box {
  border-radius: 10px;
  border: #ccc solid 1px;
  z-index: 9;
  background: #fafbfd;
  display: flex;
  margin: 8px;
  justify-content: space-between;
  width: calc(100% - 16px);
  flex-direction: column;
  position: absolute;
}

.cq-header-title {
  width: 100%;
  padding: 8px;
  padding-left: 16px;
  padding-right: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.cq-header {
  width: 100%;
  padding: 8px;
  line-height: 40px;
  color: #121212;
  box-sizing: border-box;
  z-index: 2;
  position: relative;
}
.cq-body {
  margin-top: 75px;
  margin-left: 8px;
  margin-right: 8px;
  height: calc(100% - 91px);
  box-sizing: border-box;
  display: flex;
  flex: 1;
  justify-content: space-between;
  color: #121212;
  background: #fefefe;
}

.cq-side {
  height: 100%;
  padding: 10px;
  background-color: #fafbfd;
}

.cq-result {
  margin: 0 5px;
  height: 100%;

  background-color: #fafbfd;
  overflow: scroll;

  flex: 1;
  display: flex;
}

.empty-div {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  align-content: center;
}

.empty-tip {
  font-size: 1.8rem;
  font-weight: 700;
}

.downIcon {
  height: 100px;
  width: 100px;
  font-size: 50px;
}

.result-div {
  width: 100%;
  height: 100%;
  padding: 20px;
}

.result-table {
  width: 100%;
}

.table-div {
  width: 100%;
}

.page-div {
  width: 100%;
  height: 35px;
  margin-top: 30px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  align-content: center;
}
</style>
